import React, { useState, useEffect } from 'react';
import type { GameItem } from '../types';
import { itemAPI } from '../services/api';

interface GameInventoryProps {
  onItemUse?: (itemId: string) => void;
}

const GameInventory: React.FC<GameInventoryProps> = ({ onItemUse }) => {
  const [inventory, setInventory] = useState<GameItem[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>('');
  const [selectedItem, setSelectedItem] = useState<GameItem | null>(null);

  // 加载物品列表
  const loadInventory = async () => {
    setIsLoading(true);
    setError('');
    try {
      const response = await itemAPI.getInventory();
      if (response.success && response.data) {
        setInventory(response.data);
      } else {
        setError('加载物品失败: ' + (response.message || '未知错误'));
      }
    } catch (err) {
      console.error('Failed to load inventory:', err);
      setError('加载物品失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 使用物品
  const handleUseItem = async (item: GameItem) => {
    if (onItemUse) {
      onItemUse(item.id);
    } else {
      setIsLoading(true);
      try {
        const response = await itemAPI.useItem(item.id);
        if (response.success) {
          // 重新加载物品列表
          await loadInventory();
        } else {
          setError('使用物品失败: ' + (response.message || '未知错误'));
        }
      } catch (err) {
        console.error('Failed to use item:', err);
        setError('使用物品失败，请稍后重试');
      } finally {
        setIsLoading(false);
      }
    }
  };

  // 组件挂载时加载物品
  useEffect(() => {
    loadInventory();
  }, []);

  // 刷新物品列表
  const refreshInventory = () => {
    loadInventory();
  };

  return (
    <div className="game-inventory">
      <div className="inventory-header">
        <h3>储物袋</h3>
        <button 
          className="refresh-button"
          onClick={refreshInventory}
          disabled={isLoading}
          title="刷新物品列表"
        >
          {isLoading ? '刷新中...' : '🔄'}
        </button>
      </div>

      {error && (
        <div className="inventory-error">
          {error}
        </div>
      )}

      {isLoading && (
        <div className="inventory-loading">
          正在加载物品...
        </div>
      )}

      <div className="inventory-items">
        {inventory.length === 0 && !isLoading ? (
          <div className="inventory-empty">
            <p>储物袋空空如也</p>
          </div>
        ) : (
          inventory.map((item) => (
            <div 
              key={item.id} 
              className={`inventory-item ${selectedItem?.id === item.id ? 'selected' : ''}`}
              onClick={() => setSelectedItem(item)}
            >
              <div className="item-icon">💎</div>
              <div className="item-info">
                <div className="item-name">{item.name}</div>
                <div className="item-type">{item.type}</div>
                <div className="item-description">{item.description}</div>
                {item.quantity > 1 && (
                  <div className="item-quantity">数量: {item.quantity}</div>
                )}
                {item.effect && (
                  <div className="item-effect">效果: {item.effect}</div>
                )}
              </div>
              <button 
                className="use-item-button"
                onClick={(e) => {
                  e.stopPropagation();
                  handleUseItem(item);
                }}
                disabled={isLoading}
                title="使用物品"
              >
                使用
              </button>
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default GameInventory;